package com.douwong.student.fragment;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.douwong.student.R;
import com.douwong.student.activity.CourseTabActivity;
import com.douwong.student.activity.MainActivity;
import com.douwong.student.activity.NoticActivity;
import com.douwong.student.activity.PersonInfoActivity;
import com.douwong.student.application.BaseApplication;
import com.douwong.student.base.BaseFragment;
import com.douwong.student.contant.Config;
import com.douwong.student.contant.NetConfig;
import com.douwong.student.model.NoticeObj;
import com.douwong.student.model.PrepareBean;
import com.douwong.student.model.StatusCode;
import com.douwong.student.utils.NetUtils;
import com.douwong.student.utils.ToastUtils;

import org.apache.http.message.BasicNameValuePair;

import java.util.ArrayList;
import java.util.List;

/**
 * @autor yichao
 * @time 2017/3/2215:04
 * @des 主页
 */
@SuppressLint("ValidFragment")
public class HomeFragment extends BaseFragment implements View.OnClickListener {

    private RelativeLayout mRlMyInfo, mRlEbook, mRlCouretab;

    private LinearLayout mLlNotice;
    private ImageView mIvMyInfo;
    private boolean isRunning = true, loopNoticeDisplaying = false;
    private TextView mTvNotice;
    private String [] arrnotices;
    private MainActivity mMainActivity;

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        mMainActivity = (MainActivity) activity;
    }

    @Override
    protected View getRootView(LayoutInflater inflater, ViewGroup container) {
        View contenView = View.inflate(getActivity(), R.layout.fragment_home, null);
        mRlMyInfo = (RelativeLayout) contenView.findViewById(R.id.main_home_myinfo);
        mIvMyInfo = (ImageView) contenView.findViewById(R.id.myinfoicon_icon);
        mRlCouretab = (RelativeLayout) contenView.findViewById(R.id.main_home_coursetab);
        mRlEbook = (RelativeLayout) contenView.findViewById(R.id.main_home_ebook);
        mLlNotice = (LinearLayout) contenView.findViewById(R.id.main_home_notice);
        mTvNotice= (TextView) contenView.findViewById(R.id.text_homefragment_notice);
        return contenView;
    }

    IntentFilter mIntentFilter = new IntentFilter() {
        {
            addAction(Config.LOGIN_SUCCESS);
        }
    };

    BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            switch (intent.getAction()) {
                case Config.LOGIN_SUCCESS:
                    if (BaseApplication.sUserBean != null && BaseApplication.sUserBean.getPersonalbean() != null) {
                        int sex = BaseApplication.sUserBean.getPersonalbean().getSex();
                        mIvMyInfo.setImageResource(sex == 0 ? R.mipmap.home_myinfoicon_male : R.mipmap.girl);
                    }

                    break;


            }

        }
    };

    @Override
    protected void initEvent() {
        super.initEvent();
        mRlMyInfo.setOnClickListener(this);
        mRlCouretab.setOnClickListener(this);
        mRlEbook.setOnClickListener(this);
        mLlNotice.setOnClickListener(this);
    }

    @Override
    protected void initData() {
        super.initData();
        getActivity().registerReceiver(mReceiver, mIntentFilter);

    }

    @Override
    public void onClick(View v) {
        Intent intent;
        switch (v.getId()) {
            case R.id.main_home_myinfo:
                intent=new Intent(getActivity(), PersonInfoActivity.class);
                getActivity().startActivityForResult(intent, MainActivity.SetPersonInfoQuesCode);
                break;
            case R.id.main_home_notice:

                if (!BaseApplication.isLogin){
                    ToastUtils.makeText(getContext(),"请登录");
                    mMainActivity.startLogingActivityForResult();

                    return;
                }
                intent =new Intent(getActivity(), NoticActivity.class);
                getActivity().startActivityForResult(intent,MainActivity.NoticeQuestCode);
                break;
            case R.id.main_home_coursetab:
                //课程表
                if (!BaseApplication.isLogin){
                ToastUtils.makeText(getActivity(),"请登录");
                    mMainActivity.startLogingActivityForResult();
                return;
            }
                 intent=new Intent(getActivity(), CourseTabActivity.class);
                getActivity().startActivity(intent);
                break;
            case R.id.main_home_ebook:

                break;


        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode==MainActivity.SetPersonInfoQuesCode && resultCode==MainActivity.SetPersonInfoResponeCode){
            MainActivity  mainActivity= (MainActivity) getActivity();
            mainActivity.changeLogin();
        }else if (requestCode==MainActivity.NoticeQuestCode && resultCode==MainActivity.NoticeResponeCode){
            //
            loopNoticeDisplaying=false;
            getNoticeList();
        }
    }

    Handler handle = new Handler() {
        public void handleMessage(android.os.Message msg) {
            if (arrnotices!=null){
            mTvNotice.setText(arrnotices[msg.what]+"");
            }

        };
    };



    /**
     * 获取通知栏
     */
    public void getNoticeList() {
        if (!loopNoticeDisplaying) {
            loopNoticeDisplaying = true;
        } else {
            return;
        }
        if (!isRunning) {
            isRunning = true;
        }

        new Thread(new Runnable() {

            @Override
            public void run() {
                // TODO Auto-generated method stub
                List<BasicNameValuePair> ps = new ArrayList<BasicNameValuePair>();
                ps.add(new BasicNameValuePair("object", "3"));

                if(BaseApplication.sUserBean.getClassbean()!=null){
                    ps.add(new BasicNameValuePair("objectId",BaseApplication.sUserBean.getClassbean().getId()+ ""));

                }else{
                    return;
                }

               String result = NetUtils.httpGet(NetConfig.NOTICE_LIST, ps);

                if (result != null) {
                    StatusCode<PrepareBean> sc = (StatusCode<PrepareBean>) JSON.parseObject(result,
                            new TypeReference<StatusCode<PrepareBean>>() {
                            });
                    if (sc != null && sc.isFlag()) {
                        ArrayList<NoticeObj> notices = (ArrayList<NoticeObj>) JSON.parseArray(sc.getData().getRows(),
                                NoticeObj.class);
                        if (notices != null && notices.size() > 0) {
                            arrnotices = new String[notices.size()];
                            for (int i = 0; i < notices.size(); i++) {
                                if (notices.get(i).getHaTitle() != null && !notices.get(i).getHaTitle().equals("")) {
                                    arrnotices[i] = notices.get(i).getHaTitle();
                                }
                            }
                            // handle.sendEmptyMessage(0);
                            new Thread() {
                                @Override
                                public void run() {
                                    super.run();
                                    int i = 0;
                                    while (isRunning) {
                                        handle.sendEmptyMessage(i);
                                        i++;
                                        try {
                                            Thread.sleep(3000);
                                        } catch (InterruptedException e) {
                                            e.printStackTrace();
                                        }
                                        if (i == arrnotices.length) {
                                            i = 0;
                                        }
                                    }
                                }

                            }.start();

                        }

                    }
                }

            }
        }).start();

    }

    /**
     * 注销登录的状态
     */
    public void userUnRegisterLogin() {
        isRunning = false;
        loopNoticeDisplaying = false;
        mTvNotice.setText("");
    }
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        loopNoticeDisplaying = false;
        isRunning = false;
        if (mReceiver!=null){
            getActivity().unregisterReceiver(mReceiver);
            mReceiver=null;
        }



    }
}
